<?php
/** 驴妈妈的导入产品接口 抄自api/LvMaMa.class.php 略有修改
 * Created by PhpStorm.
 * User: KaZeline
 * Date: 15-9-17
 * Time: 上午8:36
 */

namespace Api;

class LvMaMa{
    private $appKey = 'PIAOFUTONG';
    private $secret = 'e9c0c9f27762474d76a025238a158065';
    private $lmm_URL = 'http://api.lvmama.com/distributorApi/2.0/api/';

    public function share_array(){
        $time = time();
        $request_array = array(
            'timestamp' 	=> $time,
            'appKey' 		=> $this->appKey,
            'messageFormat' => 'xml',
            'sign'			=> md5($this->secret.$time.$this->secret)
        );
        return $request_array;
    }

    //批量景区基本信息接口
    public function scenicInfoListByPage($page=1){

        $action  = 'ticketProd/scenicInfoListByPage';

        $request_array = $this->share_array();
        $request_array['currentPage'] = $page;
        $request_lmm  = $this->lmm_post($action,$request_array,true);
        return $request_lmm;

    }

    //批量产品/商品信息接口
    public function productInfoListByPage($page=1){
        $action  = 'ticketProd/productInfoListByPage';
        $request_array = $this->share_array();
        $request_array['currentPage'] = $page;
        $request_lmm  = $this->lmm_post($action,$request_array);
        $productidss  = $this->objectToArray($request_lmm);
        return $productidss;
    }
    //批量产品/商品信息接口
    public function objectToArray($request_lmm){
    foreach($request_lmm->productList as $key=> $request )
    {
            foreach($request as $return )
            {
                $productids["id"]   = $return->productId;
                $productids['Name'] = $return->productName;
                $productidss['list'][] = $productids;
            }
    }
        return $productidss;
    }
    //批量价格/库存信息接口
    public function productPriceListByPage(){
        $action  = 'ticketProd/productPriceListByPage';
        $request_array = $this->share_array();
        $request_array['currentPage']	= 2;
        $request_array['beginDate']		= '2015-08-25';
        $request_array['endDate'] 		= '2015-12-31';
        $request_lmm  = $this->lmm_post($action,$request_array);
        return $request_lmm;
    }
    //按ID获取产品信息接口   景区
    public function productInfoList($lid,$flase=false){
        $action  = 'ticketProd/productInfoList';
        $request_array = $this->share_array();
        $request_array['productIds'] = $lid;
        $request_lmm  = $this->lmm_post($action,$request_array);
        if($flase==false)
        {
            $productidss  = $this->objectToArray($request_lmm);
            return $productidss;
        }
       else{
           return $request_lmm;
       }
    }
    //按ID获取商品信息接口   票类
    public function goodInfoList($tid){
        $action  = 'ticketProd/goodInfoList';

        $request_array = $this->share_array();
        $request_array['goodsIds'] = $tid;

        $request_lmm  = $this->lmm_post($action,$request_array);
        return $request_lmm;
    }
    //按ID获取价格库存接口
    public function goodPriceList($tid){
        $action  = 'ticketProd/goodPriceList';

        $request_array = $this->share_array();
        $request_array['goodsIds']	= $tid;
        $request_array['beginDate']	= date('Y-m-d', $_SERVER['REQUEST_TIME']);
        $request_array['endDate'] 	= date('Y-m-d', strtotime("{$request_array['beginDate']} + 1 month"));
        $request_lmm  = $this->lmm_post($action,$request_array);
        return $request_lmm;
    }


    //订单校验接口
    public function validateOrder($submit_array){
        $action  = 'ticket/validateOrder';

        $request_array  = $this->share_array();
        $orderInfo=<<<xml
<request>
	<orderInfo>
		<partnerOrderNo>{$submit_array['partnerOrderNo']}</partnerOrderNo>
		<orderAmount>{$submit_array['orderAmount']}</orderAmount>
		<product>
			<productId>{$submit_array['productId']}</productId>
			<goodsId>{$submit_array['goodsId']}</goodsId>
			<quantity>{$submit_array['quantity']}</quantity>
			<visitDate>{$submit_array['visitDate']}</visitDate>
			<sellPrice>{$submit_array['sellPrice']}</sellPrice>
		</product>
		<booker>
			<name>{$submit_array['name']}</name>
			<mobile>{$submit_array['mobile']}</mobile>
			<email></email>
		</booker>
		<travellers>
			{$submit_array['travellers']}
		</travellers>
	</orderInfo>
</request>
xml;
        $request_array['request']	= $orderInfo;
        $request_lmm_xml  = $this->lmm_post($action,$request_array);
        if((int)$request_lmm_xml->state->code == 1000){
            $createOrder = $this->createOrder($orderInfo);
            return $createOrder;
        }else{
            $this->logfile($submit_array['partnerOrderNo'].'|'.(int)$request_lmm_xml->state->code.'|'.(string)$request_lmm_xml->state->message,'validateOrder_fail');
            exit("101|0|0|0|0|0");
        }
    }

    //创建订单
    public function createOrder($orderInfo){
        $action  = 'ticket/createOrder';
        $request_array  = $this->share_array();
        $request_array['request']	= $orderInfo;
        $request_lmm_xml  = $this->lmm_post($action,$request_array);
        return $request_lmm_xml;
    }

    //支付订单
    public function orderPayment($partnerOrderNo,$orderId){
        $action  = 'order/orderPayment';
        $serialNum = time();
        $request_array  = $this->share_array();
        $request =<<<xml
			<request>
				<order>
					<partnerOrderNo>{$partnerOrderNo}</partnerOrderNo>
					<orderId>{$orderId}</orderId>
					<serialNum>{$serialNum}</serialNum>
				</order>
			</request>
xml;
        $request_array['request']	= $request;
        $request_lmm  = $this->lmm_post($action,$request_array);
        if((int)$request_lmm->state->code == 1000){
            $this->logfile($partnerOrderNo.'|'.$orderId,'orderPayment_success');
        }else{
            $this->logfile($partnerOrderNo.'|'.$orderId.'|'.(int)$request_lmm->state->code.'|'.(string)$request_lmm->state->message,'orderPayment_fail');
        }
    }

    //查询订单
    public function getOrderInfo(){
        $action  = 'order/getOrderInfo';
        $request_array  = $this->share_array();
        $request = <<<xml
		<request>
			<order>
				<partnerOrderNos>pft144065809464553485</partnerOrderNos>
			</order>
		</request>
xml;
        $request_array['request']	= $request;
        $request_lmm  = $this->lmm_post($action,$request_array);
        print_r($request_lmm);
    }

    //重发凭证
    public function resendCode(){
        $action  = 'order/resendCode';
        $request_array  = $this->share_array();
        $request = <<<xml
		<request>
			<order>
				<partnerOrderNo>pft144065809464553485</partnerOrderNo>
				<orderId>20019989</orderId>
			</order>
		</request>
xml;
        $request_array['request']	= $request;
        $request_lmm  = $this->lmm_post($action,$request_array);
        print_r($request_lmm);
    }

    //修改取消订单
    public function orderCancel($partnerOrderNo,$orderId){
        $action  = 'ticket/orderCancel';
        $request_array  = $this->share_array();
        $request_array['PartnerOrderNo'] = $partnerOrderNo;
        $request_array['orderId'] =  $orderId;
        $request_lmm  = $this->lmm_post($action,$request_array);
        print_r($request_lmm);
        if((int)$request_lmm->state->code == 1000){
            $this->logfile($partnerOrderNo.'|'.$orderId,'orderCancel_success');
            return 100;
        }else{
            $this->logfile($partnerOrderNo.'|'.$orderId.'|'.(int)$request_lmm->state->code.'|'.(string)$request_lmm->state->message,'orderCancel_fail');
            return 101;
        }
    }

    //请求接口服务的名称:门票景点详情
    public function TicketSenicSpotInfo($productid){
        $this->post_array['RequestType']="TicketSenicSpotInfo";
        $time = time();
        $Lvmama_RequestData = $this->productInfoList($productid,true);
        $sid  = (int)$Lvmama_RequestData->productList->product->placeId[0];
        $lid  = (int)$Lvmama_RequestData->productList->product->productId[0];
        $lmama= file_get_contents("Lvmama_All.txt");
        $co   = strpos($lmama,"<scenicId>".$sid);
        $Lvmama_content=substr($lmama,$co-20);
        $coa  = strpos($Lvmama_content,"</place>");
        $Lvmama_con = substr($Lvmama_content,0,$coa+10);
        $Lvmama_con = simplexml_load_string( $Lvmama_con, 'SimpleXMLElement', LIBXML_NOCDATA );
        $data       = array();
        foreach($Lvmama_RequestData as $c)
        {
            $data[$lid]['land']=array(
                'product_type'  => "A",
                'product_name'  => (string)$c->product->productName,
                'city'          => (string)$Lvmama_con->placeProvince.'|'.(string)$Lvmama_con->placeCity,
                'address'       => (string)$Lvmama_con->placeToAddr,
                'product_level' => (string)$Lvmama_con->placeLevel,
                'tel'           => "",
                'fax'           => "",
                'opentime'      => (string)$Lvmama_con->openTimes->openTime->sightStart,
                'runtime'       => (string)$Lvmama_con->openTimes->openTime->sightStart.'-'.(string)$Lvmama_con->openTimes->openTime->sightEnd,
                'imgpath'       => (string)$c->product->images->image[0],
                'lat'           => (string)$Lvmama_con->googleData->latitude,//纬度
                'lng'           => (string)$Lvmama_con->googleData->longitude,//经度
                'detail'        => (string)$c->product->introdution,
                'notice'        => (string)$c->product->postList->post->postInfo.
                           "<br/>".(string)$c->product->bookingInfo->explanation.
                           "<br/>".(string)$c->product->bookingInfo->freePolicy.
                           "<br/>".(string)$c->product->bookingInfo->offerCrowd,
            );
        }
        $goodsIds=(string)$Lvmama_RequestData->productList->product->goodsIds;
        $goodid=explode(",",$goodsIds);
        foreach($goodid as $good)
        {
            $Lvmama_goodid=$this->goodPriceList($good);//获取票类的价格配置
            $Lvmama_RequestDatas = $this->goodInfoList($good);//分别搜索产品的信息
            $delay[]=((int)$Lvmama_goodid->priceList->product->goodsList->goods->prices->price->aheadHour);
            $data[$lid]['land']['product_id'] =(int)$Lvmama_RequestDatas->goodsList->goods->productId;
            $ltid = (int)$Lvmama_RequestDatas->goodsList->goods->productId;
            $data[$ltid]['tickets'][]=array(
                'id'                =>(int)$Lvmama_RequestDatas->goodsList->goods->goodsId,
                'ticket_name'       =>(string)$Lvmama_RequestDatas->goodsList->goods->standardName.'('.
                                      (string)$Lvmama_RequestDatas->goodsList->goods->goodsName.')',
                'get_ticket_info'   =>(string)$Lvmama_RequestDatas->goodsList->goods->costInclude."<strong>重要信息：".
                                     (string)$Lvmama_RequestDatas->goodsList->goods->importentPoint.
                         "</strong><br/>取票时间:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->getTicketTime.
                         "<br/>取票地点:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->getTicketPlace.
                         "<br/>入园方式:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->ways.
                         "<br/>有效期:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->effectiveDesc,
                'notes'             =>"<strong>重要信息：".(string)$Lvmama_RequestDatas->goodsList->goods->importentPoint.
                          "</strong><br/>取票时间:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->getTicketTime.
                          "<br/>取票地点:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->getTicketPlace.
                          "<br/>入园方式:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->ways.
                          "<br/>有效期:".(string)$Lvmama_RequestDatas->goodsList->goods->notice->effectiveDesc,
                'payment_type'      => (string)$Lvmama_RequestDatas->goodsList->goods->paymentType=='online' ? 1 : 0,//1在线支付
                'total_storage'     =>(int)$Lvmama_goodid->priceList->product->goodsList->goods->prices->price->stock,
                'auto_cancel_minute'=>120,
                'use_delay_type'    =>0,//当天有效
                'use_delay_days'    =>30,//当天有效
                'book_early_days'   =>ceil(((int)$Lvmama_goodid->priceList->product->goodsList->goods->prices->price->aheadHour)/1440),//资源提前预定天数
                'book_deadline'     =>(string)$Lvmama_RequestDatas->goodsList->goods->notice->enterLimit->limitTime,//提前预订截止时间
                'refundcharge'      =>(string)$Lvmama_RequestDatas->goodsList->goods->rules->rule->deductionValue,//退票手续费
                'idcard_verify'     =>"",
                'buy_min_num'       =>(int)$Lvmama_RequestDatas->goodsList->goods->minimum,
                'buy_max_num'       =>(int)$Lvmama_RequestDatas->goodsList->goods->maximum,
                'verify_start_time' =>'',
                'market_price'      =>(int)$Lvmama_goodid->priceList->product->goodsList->goods->prices->price->marketPrice,
                'update_time'       => date('Y-m-d H:i:s'),
                'Mpath'             =>'http://10.160.4.140/new/d/module/api/LvMaMa/LvMaMa_get_data.php',//驴妈妈的都是这个
                'sourceT'           =>2,//同上
                'price_array'       => array(
                    'start_date'        =>  date('Y-m-d', $_SERVER['REQUEST_TIME']),
                    'end_date'          => date('Y-12-31', $_SERVER['REQUEST_TIME']),
                    'valid_week'        => '0,1,2,3,4,5,6',
                    'storage'           => -1,
                    'supply_price'      =>(int)$Lvmama_goodid->priceList->product->goodsList->goods->prices->price->sellPrice*100,
                    'retail_price'      =>(int)$Lvmama_goodid->priceList->product->goodsList->goods->prices->price->marketPrice*100,
                    'ptype'             =>0,
                ));
        };
        $delaytime=max($delay);
        $data[$lid]['land']['delaytime']  =floor($delaytime/60).'|'.$delaytime%60;//延时
        return($data);
    }
    //提交
    public function lmm_post($action,$request_array,$flag=false){
        $request_data  = http_build_query($request_array);
        $url = $this->lmm_URL.$action;
        // echo $url.'?'.$request_data;exit;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $result = curl_exec($ch);
        if($flag)return $result;
        else
        $result = simplexml_load_string( $result, 'SimpleXMLElement', LIBXML_NOCDATA );
        return $result;
    }

    public function logfile($txt,$logname){
        $fp = fopen('/var/www/html/new/d/logs/api/LvMaMa/'.$logname.date('Y-m-d').'.txt',"a");
        flock($fp, LOCK_EX) ;
        fwrite($fp,date('Y-m-d H:i:s').'|'.$txt."\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
    public static function raw_post($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        return curl_exec($ch);
    }
}

//$lv = new LvMaMa();
////$land_single = $lv->productInfoList(108874);//根据ID获取景区
////$land = $lv->scenicInfoListByPage();//获取景区信息
//$ticket = $lv->productInfoListByPage(1);//获取票类信息
//echo '<pre>';
//var_export($ticket);
//echo '</pre>';
//
//exit;
////景区信息模版
//SimpleXMLElement::__set_state(array(
//    'state' =>
//        SimpleXMLElement::__set_state(array(
//            'code' => '1000',
//            'message' => '成功',
//            'solution' => '接口访问成功',
//        )),
//    'totalPage' => '13535',
//    'scenicNameList' =>
//        SimpleXMLElement::__set_state(array(
//            'place' =>
//                array (
//                    0 =>
//                        SimpleXMLElement::__set_state(array(
//                            'scenicId' => '1',
//                            'scenicName' => '北京',
//                            'placeTown' =>
//                                SimpleXMLElement::__set_state(array(
//                                )),
//                            'placeXian' =>
//                                SimpleXMLElement::__set_state(array(
//                                )),
//                            'placeCity' => '北京',
//                            'placeProvince' => '北京',
//                            'placeCountry' => '中国',
//                            'baiduData' =>
//                                SimpleXMLElement::__set_state(array(
//                                    'longitude' => '107.768032',
//                                    'latitude' => '29.333282',
//                                )),
//                        )),
//                )
//        )),
//));
////票类信息模版
//SimpleXMLElement::__set_state(array(
//    'state' =>
//        SimpleXMLElement::__set_state(array(
//            'code' => '1000',
//            'message' => '成功',
//            'solution' => '接口访问成功',
//        )),
//    'totalPage' => '14',
//    'productList' =>
//        SimpleXMLElement::__set_state(array(
//            'product' =>
//                array (
//                    0 =>
//                        SimpleXMLElement::__set_state(array(
//                            'productId' => '108874',
//                            'placeId' => '436174',
//                            'placeName' =>
//                                SimpleXMLElement::__set_state(array(
//                                    'mainName' => 'syuu景点11',
//                                )),
//                            'productName' => 'syuu供应商打包-赠保险',
//                            'productType' => 'category_comb_ticket',
//                            'productStatus' => 'true',
//                            'goodsList' =>
//                                SimpleXMLElement::__set_state(array(
//                                    'goods' =>
//                                        SimpleXMLElement::__set_state(array(
//                                            'standardName' => '供应商打包规格',
//                                            'goodsId' => '1242517',
//                                            'goodsName' => '供应商打包规格 儿童票【出境BU】',
//                                            'goodsSort' => 'common',
//                                            'status' => 'true',
//                                            'paymentType' => 'online',
//                                            'ticketType' => 'CHILDREN',
//                                            'adultTicket' => '0',
//                                            'childTicket' => '1',
//                                            'goodsType' => 'NOTICETYPE_DISPLAY',
//                                            'certificate' => 'SMS',
//                                            'effective' => '1',
//                                            'rules' =>
//                                                SimpleXMLElement::__set_state(array(
//                                                    'rule' =>
//                                                        SimpleXMLElement::__set_state(array(
//                                                            'isChange' => 'true',
//                                                            'aheadTime' => '1440',
//                                                            'deductionType' => 'AMOUNT',
//                                                            'deductionValue' => '0.0',
//                                                        )),
//                                                )),
//                                            'minimum' => '1',
//                                            'maximum' => '10',
//                                            'costInclude' => '儿童票费用',
//                                            'notice' =>
//                                                SimpleXMLElement::__set_state(array(
//                                                    'effectiveDesc' => '指定游玩日1天内有效',
//                                                    'enterLimit' =>
//                                                        SimpleXMLElement::__set_state(array(
//                                                            'limitFlag' => 'false',
//                                                            'limitTime' => '0:00',
//                                                        )),
//                                                )),
//                                            'importentPoint' => '供应商打包规格 儿童票【出境BU】的重要提示:预订付款后未使用，可在“我的订单”中申请退款，在游玩日前1天00:00前申请，不收取任何手续费。
//',
//                                            'booker' =>
//                                                SimpleXMLElement::__set_state(array(
//                                                    'name' => 'true',
//                                                    'mobile' => 'true',
//                                                    'email' => 'false',
//                                                )),
//                                            'traveller' =>
//                                                SimpleXMLElement::__set_state(array(
//                                                    'name' => 'TRAV_NUM_ONE',
//                                                    'mobile' => 'TRAV_NUM_ONE',
//                                                    'enName' => 'TRAV_NUM_NO',
//                                                    'email' => 'TRAV_NUM_NO',
//                                                    'credentials' => 'TRAV_NUM_NO',
//                                                )),
//                                        )),
//                                )),
//                        )),
//                )
//        )),
//));
